import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/material_order.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/material/material_order_mode.dart';
import 'package:loxen/utils/app_enum_util.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/view/material/material_order_receive/material_order_receive_widget.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:loxen/widget/my_triangle_painter.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

class _ViewModel extends BaseViewModel with MaterialOrderMixin {
  List<MaterialOrder> data;

  List<MaterialOrder> getOrder() {
    List<MaterialOrder> list = data.map((element) {
      return MaterialOrder(
          brand: Brand(id: element.brand.id, name: element.brand.name, logo: element.brand.logo),
          products: element.products);
    }).toList();
    for (MaterialOrder order in list) {
      order.products = order.products.where((element) => element.select).toList();
    }
    return list;
  }

  void delete({Function() onError}) {
    List<String> pks = [];
    for (var order in data) {
      for (var material in order.products) {
        if (material.delete) pks.add(material.id.toString());
      }
    }
    String strPks = pks.join('_');
    deleteShopcar(strPks).listen((event) {
      if (event == 200) {
        for (var order in data) {
          order.products = order.products.where((element) => !element.delete).toList();
        }
        data = data
            .where((element) => (element.products != null) && (element.products.length > 0))
            .toList();
        if (data != null && data.length == 0) {
          mState = BaseState.EMPTY;
        }
        notifyListeners();
      } else {
        if (onError != null) onError.call();
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call();
      print(stack);
    });
  }

  void selectAll(MaterialOrder order, bool select) {
    for (var data in order.products) {
      data.select = select;
    }
    notifyListeners();
  }

  void selectItem(Product products) {
    products.select = !products.select;
    notifyListeners();
  }

  void deleteItem(Product products) {
    products.delete = !products.delete;
    notifyListeners();
  }

  void deleteAll(MaterialOrder order, bool select) {
    for (var data in order.products) {
      data.delete = select;
    }
    notifyListeners();
  }

  bool isSelectAll(MaterialOrder order) {
    for (var data in order.products) {
      if (!data.select) {
        return false;
      }
    }
    return true;
  }

  bool isDeleteAll(MaterialOrder order) {
    for (var data in order.products) {
      if (!data.delete) {
        return false;
      }
    }
    return true;
  }

  void loadData() {
    if (mState == BaseState.LOADING) return;
    shopcarList().doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) {
      if (event != null && event.length > 0) {
        data = event;
        mState = BaseState.CONTENT;
      } else {
        mState = BaseState.EMPTY;
      }
    }, onError: (error, stack) {
      mState = BaseState.FAIL;
      print(stack);
    }, onDone: () => notifyListeners());
  }
}

class MaterialOrderListWidget extends StatelessWidget {
  //编辑模式
  final ValueNotifier<bool> isEdit = ValueNotifier(false);
  final ValueNotifier<OrderType> currentType = ValueNotifier(null);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_ViewModel>(
      create: (_) {
        _ViewModel _viewModel = _ViewModel();
        _viewModel.loadData();
        return _viewModel;
      },
      builder: (context, _) {
        return Scaffold(
          appBar: PreferredSize(
            preferredSize: Size(double.infinity, 95.h),
            child: Builder(
                builder: (context) => Container(
                      color: Theme.of(context).backgroundColor,
                      child: SafeArea(
                        child: Row(
                          children: <Widget>[
                            MySubassembly.getBackIcon(context,
                                color: Theme.of(context).textTheme.subtitle2.color),
                            Expanded(
                              child: Center(
                                child: Text(
                                  StringResources.ling_yang_dan,
                                  style: TextStyle(
                                      fontSize: 32.sp,
                                      color: Theme.of(context).textTheme.subtitle2.color,
                                      fontWeight: FontWeight.w700),
                                ),
                              ),
                            ),
                            MySubassembly.getSearchIcon(() {
                              if (isEdit.value) {
                                isEdit.value = false;
                              } else {
                                isEdit.value = true;
                              }
                            },
                                text: ValueListenableProvider<bool>.value(
                                  value: isEdit,
                                  builder: (context, _) {
                                    return Text(
                                      context.watch<bool>() ? '完成' : '编辑',
                                      style: TextStyle(
                                        fontSize: 28.sp,
                                        color: Colours.dark_text_gray,
                                      ),
                                    );
                                  },
                                ))
                          ],
                        ),
                      ),
                    )),
          ),
          body: SingleChildScrollView(
            child: Selector<_ViewModel, BaseState>(
                builder: (context, state, __) {
                  Widget widget = Constants.empty;
                  switch (state) {
                    case BaseState.LOADING:
                      widget = Container(height: 1000.h, child: LoadingWidget());
                      break;
                    case BaseState.EMPTY:
                      widget = EmptyWidget(title: '未添加样品', content: '快到素材中心添加心仪的样板把');
                      break;
                    case BaseState.FAIL:
                      widget = FailWidget(
                          button: '重试', onClick: () => context.read<_ViewModel>().loadData());
                      break;
                    case BaseState.CONTENT:
                      widget = Container(
                        padding: EdgeInsets.only(left: 20.w, right: 20.w),
                        child: Column(
                          children: [
                            getMaterialList(),
                            orderType(),
                            ValueListenableProvider<bool>.value(
                              value: isEdit,
                              builder: (context, _) {
                                return Container(
                                  margin: EdgeInsets.only(top: 120.h, bottom: 100.h),
                                  width: double.infinity,
                                  height: 88.h,
                                  child: FlatButton(
                                      onPressed: () async {
                                        if (isEdit.value) {
                                          bool delete = await showDialog<bool>(
                                              context: context,
                                              builder: (context) {
                                                return AlertDialog(
                                                    title: Text(StringResources.ti_shi),
                                                    content: Text(
                                                      '是否确认删除已选素材？',
                                                      style: TextStyle(
                                                          color: Theme.of(context)
                                                              .textTheme
                                                              .subtitle2
                                                              .color),
                                                    ),
                                                    actions: <Widget>[
                                                      FlatButton(
                                                        child: Text(StringResources.qu_xiao),
                                                        onPressed: () =>
                                                            Navigator.of(context).pop(),
                                                      ),
                                                      FlatButton(
                                                        child: Text(StringResources.shan_chu),
                                                        onPressed: () {
                                                          Navigator.of(context).pop(true);
                                                        },
                                                      ),
                                                    ]);
                                              });
                                          if (delete != null && delete) {
                                            context.read<_ViewModel>().delete();
                                          }
                                        } else {
                                          if (currentType.value == null) {
                                            Toast.show('请选择领样方式', context);
                                            return;
                                          }
                                          var list = context.read<_ViewModel>().getOrder();
                                          if (list == null || list[0].products.length < 1) {
                                            Toast.show('请选择要下单的样品', context);
                                            return;
                                          }
                                          bool flag =
                                              await Navigator.of(context).push(MaterialPageRoute(
                                                  builder: (_) => MaterialOrderReceiveWidget(
                                                        orderType: currentType.value,
                                                        orderList: list,
                                                      )));
                                          if (flag != null && flag) Navigator.pop(context);
                                        }
                                      },
                                      // disabledColor: Color(0xFF696C72),
                                      color: Colours.app_main,
                                      child: Text(
                                        context.watch<bool>() ? '删除' : '去下单',
                                        style: TextStyle(
                                          fontSize: 32.sp,
                                          color: Colors.white,
                                        ),
                                      )),
                                );
                              },
                            ),
                          ],
                        ),
                      );
                      break;
                  }
                  return widget;
                },
                selector: (_, value) => value.mState),
          ),
        );
      },
    );
  }

  Widget getMaterialList() {
    return Builder(builder: (context) {
      var data = context.watch<_ViewModel>().data;
      List<Widget> list = data
          .map<Widget>((entity) => Container(
                padding: EdgeInsets.only(top: 30.h),
                child: Card(
                  elevation: 5,
                  child: Container(
                    child: Padding(
                      padding: EdgeInsets.only(left: 20.w, right: 20.w),
                      child: Column(
                        children: [
                          Padding(
                            padding: EdgeInsets.only(top: 30.h),
                            child: InkWell(
                              onTap: () {
                                bool all;
                                if (isEdit.value) {
                                  all = context.read<_ViewModel>().isDeleteAll(entity);
                                } else {
                                  all = context.read<_ViewModel>().isSelectAll(entity);
                                }
                                if (isEdit.value) {
                                  context.read<_ViewModel>().deleteAll(entity, !all);
                                } else {
                                  context.read<_ViewModel>().selectAll(entity, !all);
                                }
                              },
                              child: Row(
                                children: [
                                  ValueListenableProvider<bool>.value(
                                    value: isEdit,
                                    builder: (context, _) {
                                      bool all;
                                      if (context.watch<bool>()) {
                                        all = context.select<_ViewModel, bool>(
                                            (value) => value.isDeleteAll(entity));
                                      } else {
                                        all = context.select<_ViewModel, bool>(
                                            (value) => value.isSelectAll(entity));
                                      }
                                      return Padding(
                                        padding: EdgeInsets.only(right: 20.w),
                                        child: Image.asset(
                                          all
                                              ? 'images/radio_active.png'
                                              : 'images/radio_default.png',
                                          width: 40.w,
                                          height: 40.w,
                                        ),
                                      );
                                    },
                                  ),
                                  CachedNetworkImage(
                                    imageUrl: ImageUrlUtil.getClean(entity.brand.logo),
                                    height: 24.h,
                                    fit: BoxFit.fitHeight,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: 40.h, bottom: 30.h),
                            child: Builder(builder: (context) {
                              var order = entity.products;
                              return ListView.builder(
                                  itemCount: order.length,
                                  physics: NeverScrollableScrollPhysics(),
                                  shrinkWrap: true,
                                  itemBuilder: (context, index) {
                                    var material = order[index];
                                    return Container(
                                      margin: EdgeInsets.only(top: 30.h),
                                      height: 150.w,
                                      child: InkWell(
                                        onTap: () {
                                          if (isEdit.value) {
                                            context.read<_ViewModel>().deleteItem(material);
                                          } else {
                                            context.read<_ViewModel>().selectItem(material);
                                          }
                                        },
                                        child: Row(
                                          children: [
                                            ValueListenableProvider<bool>.value(
                                              value: isEdit,
                                              builder: (context, _) {
                                                return Padding(
                                                  padding: EdgeInsets.only(right: 20.w),
                                                  child: Builder(
                                                    builder: (BuildContext context) {
                                                      var select;
                                                      if (context.watch<bool>()) {
                                                        select = context.select<_ViewModel, bool>(
                                                            (value) => material.delete);
                                                      } else {
                                                        select = context.select<_ViewModel, bool>(
                                                            (value) => material.select);
                                                      }
                                                      return Image.asset(
                                                        select
                                                            ? 'images/radio_active.png'
                                                            : 'images/radio_default.png',
                                                        width: 40.w,
                                                        height: 40.w,
                                                      );
                                                    },
                                                  ),
                                                );
                                              },
                                            ),
                                            Padding(
                                              padding: EdgeInsets.only(right: 20.w),
                                              child: ClipRRect(
                                                borderRadius: BorderRadius.circular(10.w),
                                                child: CachedNetworkImage(
                                                  width: 150.w,
                                                  height: 150.w,
                                                  imageUrl: ImageUrlUtil.getClean(
                                                      material?.cover ?? '',
                                                      w: 150),
                                                  placeholder: (_, __) => Constants.loadingIcon(),
                                                  fit: BoxFit.cover,
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    material.hsName,
                                                    style: TextStyle(
                                                      fontSize: 32.sp,
                                                      color: Colours.main_text,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                  Text(
                                                    '编号：${material.code}',
                                                    style: TextStyle(
                                                      fontSize: 28.sp,
                                                      color: Colours.main_text,
                                                    ),
                                                  ),
                                                  Text(
                                                    '规格：${material.size}',
                                                    style: TextStyle(
                                                      fontSize: 28.sp,
                                                      color: Colours.main_text,
                                                    ),
                                                  )
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    );
                                  });
                            }),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ))
          .toList();
      return Column(
        children: list,
      );
    });
  }

  Widget orderType() {
    return Container(
      margin: EdgeInsets.only(top: 16.h),
      child: Card(
        elevation: 5,
        child: Container(
          padding: EdgeInsets.only(left: 20.w, right: 20.w),
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.only(top: 30.h),
                child: Text(
                  '领样方式',
                  style: TextStyle(
                    fontSize: 32.sp,
                    fontWeight: FontWeight.bold,
                    color: Colours.main_text,
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 40.h, bottom: 20.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    ValueListenableProvider<OrderType>.value(
                      value: currentType,
                      builder: (context, _) {
                        var type = context.watch<OrderType>();
                        if (type != null && type == OrderType.TONG_CHENG_PEI_SONG) {
                          return iconText('images/tongcheng_true.png',
                              StringResources.tong_cheng_song_yang, null,
                              color: Colours.app_main);
                        } else {
                          return iconText(
                              'images/tongcheng.png',
                              StringResources.tong_cheng_song_yang,
                              () => currentType.value = OrderType.TONG_CHENG_PEI_SONG,
                              color: Colours.main_text);
                        }
                      },
                    ),
                    ValueListenableProvider<OrderType>.value(
                      value: currentType,
                      builder: (context, _) {
                        var type = context.watch<OrderType>();
                        if (type != null && type == OrderType.DAO_DIAN_QU_YANG) {
                          return iconText(
                              'images/daodian_true.png', StringResources.dao_dian_qu_yang, null,
                              color: Colours.app_main);
                        } else {
                          return iconText('images/daodian.png', StringResources.dao_dian_qu_yang,
                              () => currentType.value = OrderType.DAO_DIAN_QU_YANG,
                              color: Colours.main_text);
                        }
                      },
                    ),
                    ValueListenableProvider<OrderType>.value(
                      value: currentType,
                      builder: (context, _) {
                        var type = context.watch<OrderType>();
                        if (type != null && type == OrderType.KUAI_DI_JI_YANG) {
                          return iconText(
                              'images/kuaidi_true.png', StringResources.kuai_di_ji_yang, null,
                              color: Colours.app_main);
                        } else {
                          return iconText('images/kuaidi.png', StringResources.kuai_di_ji_yang,
                              () => currentType.value = OrderType.KUAI_DI_JI_YANG,
                              color: Colours.main_text);
                        }
                      },
                    ),
                  ],
                ),
              ),
              ValueListenableProvider.value(
                value: currentType,
                builder: (context, _) {
                  var type = context.watch<OrderType>();
                  if (type == null) {
                    return Constants.empty;
                  } else {
                    int index;
                    String str;
                    switch (type) {
                      case OrderType.TONG_CHENG_PEI_SONG:
                        index = 0;
                        str = StringResources.tong_cheng_msg;
                        break;
                      case OrderType.DAO_DIAN_QU_YANG:
                        index = 1;
                        str = StringResources.dao_dian_msg;
                        break;
                      case OrderType.KUAI_DI_JI_YANG:
                        str = StringResources.kuai_di_msg;
                        index = 2;
                        break;
                    }
                    return Column(
                      children: [
                        CustomPaint(
                          size: Size(double.infinity, 20.h),
                          painter: MyTrianglePainter(
                            color: Color(0xfff2f2f2),
                            index: index,
                            max: 3,
                            width: 40.w,
                          ),
                        ),
                        Container(
                          color: Color(0xfff2f2f2),
                          margin: EdgeInsets.only(bottom: 20.h),
                          padding: EdgeInsets.all(20.w),
                          child: Text(
                            str,
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: Colours.main_text,
                            ),
                          ),
                        ),
                      ],
                    );
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget iconText(String image, String text, Function() onClick, {color}) {
    return GestureDetector(
      onTap: onClick,
      child: Column(
        children: [
          Image.asset(
            image,
            width: 125.w,
            height: 125.w,
          ),
          Text(
            text,
            style: TextStyle(
              fontSize: 28.sp,
              color: color,
            ),
          )
        ],
      ),
    );
  }
}
